package com.libcommon.gif_compress

import android.net.Uri
import androidx.multidex.BuildConfig
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.libcommon.ext.workUI
import com.libcommon.GlobalPath
import java.io.File
import kotlin.math.min


object GifCompressManager {
    private const val TAG = "GifCompressManager"

    private fun targetTempPath() = "${GlobalPath.getGifTempPath()}/temp.gif"
    private var compressResult: ((compressPath: String) -> Unit)? = null
    private val parser by lazy { GIFMetadataParser() }
    private val options by lazy { CompressOptions() }
    private val compressListener by lazy {
        object : CompressListener {
            override fun onStart() {
                LogUtils.dTag(TAG, "Compress start")
            }

            override fun onCompleted() {
                if (BuildConfig.DEBUG) {
                    val compressGifInfo = parser.parse(Uri.parse(targetTempPath()))
                    LogUtils.iTag(TAG, "size=" + ConvertUtils.byte2FitMemorySize(compressGifInfo.fileSize))
                }
                LogUtils.dTag(TAG, "Compress onCompleted")
                workUI { compressResult?.invoke(targetTempPath()) }

            }

            override fun onFailed(exception: Throwable) {
                LogUtils.eTag(TAG, "Compress fail, msg = " + exception.message)
                workUI {
                    ToastUtils.showShort("compress fail,${exception.message}")
                    compressResult?.invoke("")
                }
            }
        }
    }

    fun startCompress(selectFilePath: String?, compressResult: (compressPath: String) -> Unit) {
        if (selectFilePath.isNullOrEmpty() || !FileUtils.isFileExists(selectFilePath)) {
            compressResult.invoke("")
            return
        }

        GifCompressManager.compressResult = compressResult
        val gifInfo = parser.parse(Uri.parse(selectFilePath))
        LogUtils.dTag(TAG, "size=${ConvertUtils.byte2FitMemorySize(gifInfo.fileSize)}")

        val targetFile = File(targetTempPath())
        FileUtils.createFileByDeleteOldFile(targetFile)

        options.apply {
            source = Uri.parse(selectFilePath)
            sink = Uri.parse(targetTempPath())
            targetWidth = min(gifInfo.width, 150)
            targetHeight = min(gifInfo.height, 150)
            targetFrameRate = min(gifInfo.frameRate, 24)
            targetGctSize = 256
            listener = compressListener
        }

        GIFCompressor.compress(Utils.getApp(), options)
    }

    fun onRelease() {
        compressResult = null
    }

}
